const userList = [];

// 获取一个没有出现过的数字
const isLive = (num) => userList.find(({ id }) => id === num) ? isLive(Math.trunc(Math.random() * 100000 + 10000)) : num;

// 获取相关用户list
const getUserList = (msg) =>userList.filter((userItem) =>
    Object.keys(msg).filter((key) =>
        Array.isArray(msg[key]) ? msg[key].some(x => userItem[key].includes(x)) : msg[key] == userItem[key]
    ).length == Object.keys(msg).length)

// 是否返回错误
const errFlag = () =>{
    return Math.random()*10>2 ? true : false
} 

// 延时两秒
const sleep =() => new Promise((resolve)=>{
    setTimeout(() => {
        resolve()
    }, Math.trunc(Math.random() *1000+1000));
})

// 创建用户
const add =async ({ 
    username,
    age = 18, 
    hobby, 
    id = isLive(Math.trunc(Math.random() * 100000 + 10000)) 
    } = obj ) => {
    await sleep();
    if(errFlag()&&getUserList({ username }).length==0){
        userList.push({ username, age, hobby, id, });
        return id
    }else{
        throw new Error('错误') 
    }
};

// 删除用户
const userDelete =async (id) =>{
    await sleep();
    if(errFlag()){
        userList.splice(userList.indexOf(getUserList( id )[0]), 1)
    }else{
        throw new Error('错误')
    }
} 

// 更改用户信息
const userUpdate =async (id, obj, user = getUserList({ id })[0] ) =>{
    await sleep();
    if(errFlag()){
        Object.keys(user).filter(item => obj[item] ? user[item] = obj[item] : false)
    }else{
        throw new Error('错误')
    }
} 
// 获取用户信息
const getUser =async (msg, page  ) =>{
    const thisUser =  getUserList(msg)
    await sleep();
    if(errFlag()){
        return { 
            pageCount:Math.ceil(thisUser.length / page.perpage),
            total:thisUser.length,
            data: thisUser.filter((item,index)=>index>=(page.page-1)*page.perpage&&index<page.page*page.perpage?item:false) 
         }
    }else{
        throw new Error('错误')
    }
} 

// 删除全部用户
const delelteAll = async () => {
    await sleep();
    if(errFlag()){
        userList.splice(0,userList.length)
    }else{
        throw new Error('错误')
    }
}

module.exports.add = add;
module.exports.delete = userDelete;
module.exports.update = userUpdate;
module.exports.get = getUser;
module.exports.delelteAll = delelteAll;
module.exports.userList = userList;